<template>
  <div class="app-container">
    <!-- 左侧树形菜单 -->

    <div class="tree-panel">
      <div class="head-container">
        <el-input
          v-model="projectName"
          placeholder="请输入培训项目"
          clearable
          size="small"
          prefix-icon="el-icon-search"
          style="margin-bottom: 20px"
          @keyup.enter.native="filterTree"
        />
      </div>
      <el-tree
        ref="tree"
        :data="projectOptions"
        :props="defaultProps"
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        node-key="id"
        default-expand-all
        highlight-current
        @node-click="handleNodeClick"
      />
    </div>

    <el-col :span="20" style="padding: 20px">
      <!-- 搜索区域 -->
      <el-form
        :model="queryParams"
        inline
        size="small"
        v-show="showSearch"
        label-width="80px"
      >
        <el-form-item label="题组">
          <el-input
            v-model="queryParams.groupName"
            placeholder="请输入题组关键词"
            clearable
            @keyup.enter.native="handleQuery"
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="题组类型">
          <el-select
            v-model="queryParams.groupType"
            placeholder="请选择题组题型"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="dict in dict.type.question_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="关联状态">
          <el-select
            v-model="queryParams.relateStatus"
            placeholder="请选择关联状态"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="dict in dict.type.relate_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="创建时间">
          <el-date-picker
            v-model="queryParams.rangeTime"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            clearable
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <!-- 按钮组 -->
        <el-col :span="24">
          <div
            style="
              display: flex;
              justify-content: space-between;
              align-items: center;
              padding: 10px 0;
            "
          >
            <!-- 左侧按钮 -->
            <div style="display: flex; gap: 10px">
              <el-button type="primary" plain @click="handleExport"
                >导出</el-button
              >
              <el-button type="primary" plain @click="handleAdd"
                >创建题组</el-button
              >
              <el-button
                type="primary"
                plain
                :disabled="single"
                @click="handleUpdate"
                >编辑题组</el-button
              >
              <el-button
                type="primary"
                plain
                :disabled="single"
                @click="handleRelate()"
                >关联题目</el-button
              >
              <el-button
                type="primary"
                plain
                :disabled="single"
                @click="handleView()"
                >查看题目</el-button
              >
              <el-button
                type="primary"
                plain
                :disabled="multiple"
                @click="handleDelete"
                >删除题组</el-button
              >
            </div>

            <!-- 右侧按钮 -->
            <div style="display: flex; gap: 10px">
              <column-config-dialog-vue
                :showSearch.sync="showSearch"
                :columns="tableColumns"
                @queryTable="getList"
              ></column-config-dialog-vue>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 表格 -->
      <el-table
        v-loading="loading"
        :data="questionGroupList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />

        <el-table-column
          label="题组"
          align="center"
          prop="groupName"
          v-if="tableColumns.find((col) => col.prop === 'groupName').visible"
        />
        <el-table-column
          label="题组类型"
          align="center"
          prop="groupType"
          v-if="tableColumns.find((col) => col.prop === 'groupType').visible"
        >
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.question_type"
              :value="scope.row.groupType"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="培训项目"
          align="center"
          prop="trainingProjectName"
          v-if="
            tableColumns.find((col) => col.prop === 'trainingProjectName')
              .visible
          "
        />
        <el-table-column
          label="题量"
          align="center"
          prop="questionCount"
          v-if="
            tableColumns.find((col) => col.prop === 'questionCount').visible
          "
        />
        <el-table-column
          label="创建人"
          align="center"
          prop="createBy"
          v-if="tableColumns.find((col) => col.prop === 'createBy').visible"
        />
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          v-if="tableColumns.find((col) => col.prop === 'createTime').visible"
        >
          <template slot-scope="scope">
            {{ scope.row.createTime }}
          </template>
        </el-table-column>
        <el-table-column
          label="备注"
          align="center"
          prop="remark"
          v-if="tableColumns.find((col) => col.prop === 'remark').visible"
        />
        <el-table-column
          label="操作"
          width="280px"
          align="center"
          class-name="small-padding fixed-width"
          v-if="tableColumns.find((col) => col.prop === 'operation').visible"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['examination:questionGroup:edit']"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="handleRelateRow(scope.row)"
              v-hasPermi="['examination:questionGroup:relate']"
              >关联题目</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="handleViewRow(scope.row)"
              v-hasPermi="['examination:questionGroup:view']"
              >查看题目</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="handleDelete(scope.row)"
              v-hasPermi="['examination:questionGroup:remove']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加或修改题组管理对话框 -->
      <el-dialog
        :title="title"
        :visible.sync="open"
        width="800px"
        custom-class="dialog-custom"
        append-to-body
      >
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <!-- 第一行：题组名称 和 题组题型 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="题组名称" prop="groupName">
                <el-input
                  v-model="form.groupName"
                  placeholder="请输入题组名称"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="题组题型" prop="groupType">
                <el-select
                  v-model="form.groupType"
                  placeholder="请选择题组题型"
                >
                  <el-option
                    v-for="dict in dict.type.question_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 第二行：项目类别 -->
          <el-form-item label="项目类别" prop="trainingProjectId">
            <el-cascader
              v-model="form.trainingProjectId"
              :options="projectOptions"
              :props="{
                checkStrictly: true,
                emitPath: false, //只传入子节点的id
                value: 'id',
                label: 'label',
                children: 'children',
              }"
              placeholder="请选择项目类别"
              clearable
            />
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitForm">提交</el-button>
        </div>
      </el-dialog>

      <!-- 关联题目 -->
      <RelateQuestionDialogVue
        :visible.sync="relateDialogVisible"
        :question-type="currentGroupType"
        :question-group-id="currentQuestionGroupId"
        :dict="dictCache"
        @confirm="handleConfirmRelate"
      />
      <!-- 查看题目 -->
      <ViewQuestionDialogVue
        :visible.sync="viewDialogVisible"
        :question-group-id="currentQuestionGroupId"
        :current-question-type="currentGroupType"
        :dict="dictCache"
      />
    </el-col>
  </div>
</template>

<script>
import {
  listQuestionGroup,
  getQuestionGroup,
  delQuestionGroup,
  addQuestionGroup,
  updateQuestionGroup,
  getListInfo,
  associationQuestion,
} from "@/api/examination/questionGroup";
import { projectTreeSelect } from "@/api/training/projects";
import ColumnConfigDialogVue from "../../../components/ColumnConfig/ColumnConfigDialog.vue";
// 关联题目
import RelateQuestionDialogVue from "../../../components/examination/RelateQuestionDialog.vue";
// 查看题目
import ViewQuestionDialogVue from "../../../components/examination/ViewQuestionDialog.vue";
export default {
  name: "QuestionGroup",
  dicts: ["question_type", "relate_status"],
  components: {
    ColumnConfigDialogVue,
    RelateQuestionDialogVue,
    ViewQuestionDialogVue,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 题组管理表格数据
      questionGroupList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        groupName: null,
        groupType: null,
        relateStatus: null,
        trainingProjectName: null,
        questionCount: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        groupName: [
          { required: true, message: "题组名称不能为空", trigger: "blur" },
        ],
        groupType: [
          { required: true, message: "题组题型不能为空", trigger: "change" },
        ],
        trainingProjectId: [
          { required: true, message: "项目类别不能为空", trigger: "change" },
        ],
      },
      //新增数据定义
      //树形结构数据
      // 所有部门树选项
      projectName: "",
      projectOptions: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 缓存字典数据
      dictCache: {
        question_type: {},
        relate_status: {},
      },
      // 列显隐
      tableColumns: [
        { prop: "groupName", label: "题组名称", visible: true },
        { prop: "groupType", label: "题组题型", visible: true },
        { prop: "trainingProjectName", label: "培训项目名称", visible: true },
        { prop: "questionCount", label: "题量", visible: true },
        { prop: "remark", label: "备注", visible: true },
        { prop: "createBy", label: "创建者", visible: true },
        { prop: "createTime", label: "创建时间", visible: true },
        { prop: "operation", label: "操作", visible: true },
      ],
      // 关联题目
      currentGroupType: "", // 当前选中的题组类型
      relateDialogVisible: false, // 控制弹窗显示
      // 查看题目
      viewDialogVisible: false,
      currentQuestionGroupId: "",
    };
  },
  created() {
    this.getList();
    this.getProjectTree();
    this.$nextTick(async () => {
      await this.loadDicts();
    });
  },
  filters: {
    formatDate(value) {
      if (value) {
        return moment(value).format("YYYY-MM-DD HH:mm:ss");
      }
      return "";
    },
  },
  methods: {
    async loadDicts() {
      this.dictCache.question_type = this.dict.label.question_type;
      this.dictCache.relate_status = this.dict.label.relate_status;
    },
    /** 查询题组管理列表 */
    getList() {
      this.loading = true;
      getListInfo(this.queryParams).then((response) => {
        this.questionGroupList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        groupId: null,
        groupName: null,
        groupType: null,
        relateStatus: null,
        trainingProjectId: null,
        trainingProjectName: null,
        questionCount: null,
        remark: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        exampleOne: null,
        exampleTwo: null,
        exampleThree: null,
        exampleFour: null,
        exampleFive: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      // 将时间范围拆分为 start 和 end
      if (this.queryParams.rangeTime) {
        this.queryParams.createStartTime = this.queryParams.rangeTime[0];
        this.queryParams.createEndTime = this.queryParams.rangeTime[1];
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        groupName: null,
        groupType: null,
        relateStatus: null,
        trainingProjectName: null,
        questionCount: null,
        projectId: this.queryParams.projectId, // 保留项目ID，因为它是通过树节点选择的
      };
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.groupId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新建题组";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const groupId = row.groupId || this.ids;
      getQuestionGroup(groupId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "编辑题组";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.groupId != null) {
            updateQuestionGroup(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addQuestionGroup(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const groupIds = row.groupId || this.ids;
      this.$modal
        .confirm('是否确认删除题组管理编号为"' + groupIds + '"的数据项？')
        .then(function () {
          return delQuestionGroup(groupIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "examination/questionGroup/export",
        {
          ...this.queryParams,
        },
        `questionGroup_${new Date().getTime()}.xlsx`
      );
    },

    //新增方法
    //树形结构
    filterTree() {
      this.$refs.tree.filter(this.projectName);
    },
    // 获取树形数据
    getProjectTree(val) {
      var params = { projectName: val };
      params.projectId = this.queryParams.projectId;
      projectTreeSelect(params).then((response) => {
        this.projectOptions = response.data;
      });
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    handleNodeClick(data) {
      this.queryParams.trainingProjectId = data.id;
      this.queryParams.pageNum = 1;
      this.getList();
    },
    flattenTree(tree) {
      let result = [];
      tree.forEach((node) => {
        result.push({ id: node.id, label: node.label });
        if (node.children && node.children.length > 0) {
          result = result.concat(this.flattenTree(node.children));
        }
      });
      return result;
    },
    // 切换搜索显示
    toggleSearch() {
      this.showSearch = !this.showSearch;
    },
    // 刷新表格数据
    refreshTable() {
      this.getList();
    },
    // 切换排序列显示
    toggleSort() {
      // 根据实际需求实现排序列的显示/隐藏逻辑
      this.$message.info("排序列功能待实现");
    },
    // 关联题目
    handleRelate() {
      const selectedRow = this.questionGroupList.find(
        (item) => item.groupId === this.ids[0]
      );
      console.log("当前题组:", selectedRow);

      if (!selectedRow) {
        this.$message.warning("请先选择题组");
        return;
      }
      this.currentQuestionGroupId = selectedRow.groupId;
      this.currentGroupType = selectedRow.groupType;
      this.relateDialogVisible = true;
    },
    // 确认关联题目
    handleConfirmRelate(selectedQuestions) {
      var params = {
        groupId: this.ids[0] || this.currentQuestionGroupId,
        questionIds: selectedQuestions.map((q) => q.questionId),
      };
      associationQuestion(params).then((response) => {
        this.$message.success("已成功关联题目");
        this.relateDialogVisible = false;
        this.getList(); // 刷新列表
      });
    },
    // 查看题目
    handleView() {
      const selectedRow = this.questionGroupList.find(
        (item) => item.groupId === this.ids[0]
      );

      if (!selectedRow) {
        this.$message.warning("请先选择题组");
        return;
      }

      this.currentQuestionGroupId = selectedRow.groupId;
      this.currentGroupType = selectedRow.groupType;
      this.viewDialogVisible = true;
    },
    // 关联题目
    handleRelateRow(row) {
      const selectedRow = row;
      console.log("当前题组:", selectedRow);
      this.currentQuestionGroupId = selectedRow.groupId;
      console.log("currentQuestionGroupId:", this.currentQuestionGroupId);
      this.currentGroupType = selectedRow.groupType; // 记录当前题组类型
   

      this.relateDialogVisible = true;
    },
    // 查看题目
    handleViewRow(row) {
      const selectedRow = row;
      if (!selectedRow) {
        this.$message.warning("请先选择题组");
        return;
      }

      this.currentQuestionGroupId = selectedRow.groupId;
      this.currentGroupType = selectedRow.groupType;
      this.viewDialogVisible = true;
    },
  },
  watch: {
    projectName(val) {
      this.$refs.tree.filter(val);
      this.getProjectTree(val);
    },
  },
};
</script>


<style scoped>
.app-container {
  display: flex;
  height: 100%;
}

.tree-panel {
  width: 360px;
  border-right: 1px solid #ebeef5;
  overflow-y: auto;
  padding: 20px;
}

.head-container {
  margin-bottom: 20px;
}

.el-form {
  margin-top: 20px;
  padding: 0 20px;
}

.el-form-item {
  margin-bottom: 10px;
}

.el-button {
  margin-right: 10px;
}

.el-table {
  margin-top: 20px;
}

.el-pagination {
  margin-top: 20px;
}
.dialog-custom {
  min-height: 500px !important;
  max-height: 600px !important;
  overflow-y: auto;
}
</style>
